package com.vrv.common.listview;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;

import com.vrv.netmgr.R;

/**
 * @Description ListView工具类
 * 
 * @author gaopei
 * @date
 */
public class ListViewUtil {
	private Activity activity;
	private ListViewAdapter adapter;
	private ArrayList<HashMap<String, Object>> listData;
	private ListView listView;
	public final static int PAGESIZE = 20;

	public ListViewUtil(Activity activity, ListViewAdapter adapter,
			ArrayList<HashMap<String, Object>> listData, ListView listView) {
		this.activity = activity;
		this.adapter = adapter;
		this.listData = listData;
		this.listView = listView;
	}

	public View loadMorePage() {
		final View loadMoreView = activity.getLayoutInflater().inflate(
				R.layout.list_page_load, null);
		final Button loadMoreButton = (Button) loadMoreView
				.findViewById(R.id.loadNextButton);
		loadMoreButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				loadMoreButton.setText("正在加载中..."); // 设置按钮文字
				new Handler().postDelayed(new Runnable() {

					@Override
					public void run() {
						loadMoreData();
						adapter.notifyDataSetChanged();
						if (adapter.getCount() == listData.size())
							listView.removeFooterView(loadMoreView);
						else
							loadMoreButton.setText("查看更多..."); // 恢复按钮文字
					}
				}, 1000);
			}
		});
		listView.addFooterView(loadMoreView); // 设置列表底部视图
		return loadMoreView;
	}

	/**
	 * 初始化ListView的适配器
	 */
	public void initializeAdapter() {

		for (int i = 0; i < listData.size() && i < PAGESIZE; i++)
			adapter.addItem(listData.get(i));
	}

	/*
	 * 加载更多数据
	 */
	private void loadMoreData() {
		int count = adapter.getCount();
		int datasize = listData.size();
		if (count + PAGESIZE <= datasize) {
			for (int i = count; i < count + PAGESIZE; i++)
				adapter.addItem(listData.get(i));
		} else {
			for (int i = count; i < datasize; i++)
				adapter.addItem(listData.get(i));
		}
	}
}